<?php
namespace Home\Controller;
use Think\Controller;

class CronController extends Controller {
    public function index() {
        $ip = get_client_ip();
	if (!in_array($ip, C("ALLOW_IPS"))) {
		return;
	}
        set_time_limit(0);
        $expire = D('Expiremsg');
        $crons = $expire->join('LEFT JOIN __USER__ ON __EXPIREMSG__.uid=__USER__.id')->select();
        if (empty($crons))
            return;
        foreach ($crons as $cron) {
            $this->execSend($cron);
        }
}
    
    private function execSend($cron) {
        $time = date('Ymd', strtotime("+{$cron['nod']}day"));
        $orgseq = $cron['orgseq'];
        $xml = getUsers($orgseq, "", $time, $time, '', '', '');
        if (empty($xml)) {
            return;
        }
        $mobiles = implode(',', $this->getMobiles($xml));
        $msgcontent = $cron['msgcontent']."【".$cron['signature']."】";
        $starttime = strtotime(date('Y-m-d').' '.$cron['sendtime']);
        $username = $cron['msgname'];
        $passwd = $cron['msgpass'];
        $apikey = $cron['msgapikey'];
        $data['status'] = sendSMS($username, $passwd, $mobiles, $msgcontent, $apikey, $starttime);
        $data['mobiles'] = $mobiles;
        $data['msgcontent'] = $msgcontent;
        $data['uid']        = $cron['uid'];
        $data['logtime']    = time();
        D('Log')->addLog($data);
    }
    
    private function getMobiles($xml) {
        $mobiles = array();
        foreach($xml as $p) {
            if(!empty($p['PHONE'])) {
                $mobiles[] = $p['PHONE'];
            }
        }
        return $mobiles;
    }
}
